package com.dtborad.myblog.controller;

import com.dtborad.myblog.common.FileUploadUtil;
import com.dtborad.myblog.common.Result;
import com.github.houbb.heaven.util.lang.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/upload")
@Slf4j
@Api(tags = "文件上传")
@CrossOrigin(origins = "*")
public class FileUploadController {
    @Autowired
    private FileUploadUtil fileUploadUtil;

    //允许上传的文件类型
    private static final Map<String, String> ALLOWED_EXTENSIONS;

    static {
        ALLOWED_EXTENSIONS = new HashMap<>();
        ALLOWED_EXTENSIONS.put("music", "mp3,wav,flac,aac,m4a,wma,ogg,oga,aiff,aif,alac,ape,amr,mid,midi");
    }

    @PostMapping
    @ApiOperation("文件上传接口")
    public Result<Object> uploadFile(@RequestParam("file") MultipartFile file,  // 文件参数
                                     @RequestParam(value = "dir", required = false) String dir  // 可选目录参数
    ) {
        log.info("文件上传:::::111::::::" + file.getOriginalFilename());
        log.info("文件上传:::::222::::::" + dir);

        // 调用工具类方法，传递文件和目录
        String fileName = file.getOriginalFilename();
        if (StringUtil.isNotBlank(fileName)) {
            if (ALLOWED_EXTENSIONS.containsKey(dir)) {
                String suffix = ALLOWED_EXTENSIONS.get(dir);
                int lastIndex = fileName.lastIndexOf(".");
                String fileSuffix = fileName.substring(lastIndex + 1);
                log.info("文件后缀:::" + fileSuffix);
                if (!suffix.contains(fileSuffix)) {
                    return Result.ofFail("500", "文件类型不支持!" + fileName);
                }
            }
            return fileUploadUtil.uploadFile(file, dir);
        }else {
            return Result.ofFail("400", "请选择文件");
        }
    }
}
